package com.itheima.sevrice.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.bean.*;
import com.itheima.common.PageParam;
import com.itheima.dao.OrderDao;
import com.itheima.dto.OrdersDto;
import com.itheima.sevrice.AddressBookService;
import com.itheima.sevrice.OrderDetailService;
import com.itheima.sevrice.OrderService;
import com.itheima.sevrice.ShoppingCartService;
import com.itheima.utils.BaseContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired(required = false)
    private OrderDao orderDao;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private ShoppingCartService shoppingCartService;


    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 订单准备数据
     *
     * @param orders
     * @param user
     * @return
     */
    public Orders prepareOrder(Orders orders, User user) {
        //1.补充数据
        //1.1订单编号
        orders.setNumber(UUID.randomUUID().toString().replaceAll("-", ""));
        //1.2订单状态
        orders.setStatus(2);//1.未付款 2.已付款 3.
        //1.3下单用户的id
        orders.setUserId(user.getId());
        //1.4下单地址id ：：不需要设置，页面已经提供
        //1.5订单的时间
        orders.setOrderTime(LocalDateTime.now());
        //1.6支付时间
        orders.setCheckoutTime(LocalDateTime.now());
        //1.7支付的方式 1.微信支付 2.支付宝支付
        orders.setPayMethod(1);
        //1.8总价 不需要提供 页面已经提供了
        //1.9备注 不需要提供 页面已经提供了
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        //1.10收货电话
        orders.setPhone(addressBook.getPhone());
        //1.11收货地址
        String province = addressBook.getProvinceName();//省份
        String city = addressBook.getCityName();//城市
        String district = addressBook.getDistrictName();//区域
        String detail = addressBook.getDetail();//详细地址
        //拼接后的完整地址
        String address = (province != null ? province : "") +
                (city != null ? city : "") +
                (district != null ? district : "") +
                (detail != null ? detail : "");
        orders.setAddress(address);
        //1.12下单用户的用户名
        orders.setUserName(user.getName());
        //1.13收货人
        orders.setConsignee(addressBook.getConsignee());
        return orders;
    }

    /**
     * 添加订单
     * 1. 需要添加订单表 和订单详情表
     *
     * @param orders
     * @return
     */
    @Override
    public int add(Orders orders, User user) {
        //调用方法 准备数据
        orders = prepareOrder(orders, user);

        //添加到订单表
        int row1 = orderDao.insert(orders);

        //添加到订单详情表::订单详情的数据是来自购物车的数据
        List<ShoppingCart> shoppingCartList = shoppingCartService.findShoppingCart();
        int row2 = 0;
        //遍历购物车的数据，取出每一件菜品| 套餐
        for (ShoppingCart cart : shoppingCartList) {
            //一件购物车对象 转化为一个 订单详情对象
            OrderDetail orderDetail = new OrderDetail();

            //设置数据
            BeanUtils.copyProperties(cart, orderDetail);

            //设置订单详情 属于哪个订单
            orderDetail.setOrderId(orders.getId());

            //添加到订单详情表
            row2 += orderDetailService.add(orderDetail);
        }

        if (row1 > 0 && row2 == shoppingCartList.size()){
            //添加成功 ,清空购物车数据
            shoppingCartService.delete();
            return 1;
        }
        return 0;
    }

    /**
     * 分页查询
     *
     * @param pageParam
     * @return
     */
    @Override
    public IPage<Orders> findPage(PageParam pageParam) {
        IPage<Orders> iPage=new Page<>();
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.like(pageParam.getNumber()!=null, Orders::getNumber,pageParam.getNumber());
        lqw.like(pageParam.getBeginTime()!=null, Orders::getOrderTime,pageParam.getBeginTime());
        lqw.like(pageParam.getEndTime()!=null, Orders::getOrderTime,pageParam.getEndTime());
        //追加排序条件 结账时间排序
        lqw.orderByDesc(Orders::getCheckoutTime);
        //得到订单的集合
        return orderDao.selectPage(iPage, lqw);


    }

    /**
     * 修改订单的状态
     *
     * @param orders
     * @return
     */
    @Override
    public int updateStatus(Orders orders) {
        LambdaUpdateWrapper<Orders> lqw = new LambdaUpdateWrapper<>();
        lqw.eq(Orders::getId,orders.getId());
        lqw.set(Orders::getStatus,orders.getStatus());
        return orderDao.update(null,lqw);
    }

    /**
     * 根据用户id 查询用户订单 分页查询
     *
     * @param pageParam
     * @return
     */
    @Override
    public IPage<OrdersDto> findUserPage(PageParam pageParam) {
        IPage<Orders> iPage=new Page<>(pageParam.getPage(),pageParam.getPageSize());
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Orders::getUserId, BaseContext.getCurrentId());
        //追加排序 条件
        lqw.orderByDesc(Orders::getCheckoutTime);
        //得到用户订单的集合
        IPage<Orders> ordersIPage = orderDao.selectPage(iPage, lqw);
        //封装orderDto 数据
        List<OrdersDto> ordersDtoList = ordersIPage.getRecords().stream().map(orders -> {
            OrdersDto ordersDto = new OrdersDto();
            //拷贝订单数据
            BeanUtils.copyProperties(orders, ordersDto);
            //根据订单id 查询订单详情里面的订单菜品数据
            List<OrderDetail> orderDetailList = orderDetailService.findByOrderId(orders.getId());
            if (orderDetailList != null) {
                ordersDto.setOrderDetails(orderDetailList);
            }
            return ordersDto;
        }).collect(Collectors.toList());
        //封装OrderDto  携带total 总记录数和当前页的集合数
        IPage<OrdersDto> dtoIPage=new Page<>();
        dtoIPage.setTotal(ordersIPage.getTotal());
        dtoIPage.setRecords(ordersDtoList);
        return dtoIPage;

    }

    /**
     * 再来一单
     *  先清除之前购物车的数据 在把再来一单中的菜品数据重新写入购物车中
     * @param id
     * @return
     */
    @Override
    public List<ShoppingCart> again(Long id) {
        //根据订单的id 查询订单菜品详情
        List<OrderDetail> orderDetailList = orderDetailService.findByOrderId(id);
        //得到用户的id
        long userId = BaseContext.getCurrentId();
        //遍历每一个订单详情，封装成每一个订单
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(orderDetail -> {
            //构建一个购物车
            ShoppingCart shoppingcart = new ShoppingCart();

            //shoppingcart.setName(orderDetail.getName());
            //shoppingcart.setImage(orderDetail.getImage());
            //shoppingcart.setNumber(orderDetail.getNumber());
            //shoppingcart.setAmount(orderDetail.getAmount());

            //拷贝数据到购物车
            BeanUtils.copyProperties(orderDetail, shoppingcart);

            Long dishId = orderDetail.getDishId();
            Long setmealId = orderDetail.getSetmealId();
            String dishFlavor = orderDetail.getDishFlavor();
            if (dishId != null) {
                shoppingcart.setDishId(dishId);
                shoppingcart.setDishFlavor(dishFlavor);
            } else {
                shoppingcart.setSetmealId(setmealId);
            }
            //补充数据，重新设置新的数据
            shoppingcart.setId(null);
            shoppingcart.setUserId(userId);
            shoppingcart.setCreateTime(LocalDateTime.now());
            return   shoppingCartService.add(shoppingcart);

           // return shoppingcart;
        }).collect(Collectors.toList());

        return shoppingCartList;
    }


}
